package net.hualisheng.netty.process;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MultiProcess {

    private static final ExecutorService service = Executors.newFixedThreadPool(2 * Runtime.getRuntime().availableProcessors());

    private Selector selector;

    public MultiProcess() throws IOException {
        selector = SelectorProvider.provider().openSelector();
        start();

    }
    public void addChannel(SocketChannel channel) throws ClosedChannelException {
        channel.register(selector,SelectionKey.OP_READ);
    }
    public void wakeUp(){
        this.selector.wakeup();
    }

    public void start() {
//        service.submit(() -> {
//            while (true) {
//                if (selector.select(500) <= 0) {
//                    continue;
//                }
//                Set<SelectionKey> keys = selector.selectedKeys();
//                Iterator<SelectionKey> iterator = keys.iterator();
//                while (iterator.hasNext()) {
//                    SelectionKey selectionKey = iterator.next();
//                    iterator.remove();
//                    if (selectionKey.isReadable()) {
//                        ByteBuffer buffer = ByteBuffer.allocate(1024);
//                        SocketChannel channel = (SocketChannel) selectionKey.channel();
//                        int read = channel.read(buffer);
//                        if (read < 0) {
//                            channel.close();
//                            continue;
//                        } else if (read == 0) {
//                            continue;
//                        } else {
//                            System.out.println("waiting");
//                        }
//                    }
//                }
//            }
//        });
    };

}
